package com.lightboat.web.controller.crm;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Maps;
import com.lightboat.common.annotation.Log;
import com.lightboat.common.api.BaiDuJianKangApi;
import com.lightboat.common.core.controller.BaseController;
import com.lightboat.common.core.domain.AjaxResult;
import com.lightboat.common.core.page.TableDataInfo;
import com.lightboat.common.enums.BusinessType;
import com.lightboat.common.utils.DateUtils;
import com.lightboat.common.utils.PageUtils;
import com.lightboat.common.utils.poi.ExcelUtil;
import com.lightboat.system.domain.CrmComment;
import com.lightboat.system.domain.request.CrmCommentQueryRequest;
import com.lightboat.system.service.ICrmCommentService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ForkJoinPool;

/**
 * 评论Controller
 *
 * @author lightboat
 * @date 2025-08-21
 */
@Tag(name = "评论")
@RestController
@RequiredArgsConstructor
@RequestMapping("/system/comment")
public class CrmCommentController extends BaseController {

    private final ICrmCommentService crmCommentService;

    /**
     * 查询评论列表
     */
    @Operation(summary = "查询评论列表")
    @PreAuthorize("@ss.hasPermi('customerService:evaluate:list')")
    @GetMapping("/list")
    public TableDataInfo<CrmComment> list(CrmCommentQueryRequest request) {
        PageUtils.<CrmComment>chainOrderBy().orderBy(CrmComment::getCreateTime, false).apply();
        startPage();
        CrmComment crmComment = BeanUtil.copyProperties(request, CrmComment.class);
        if (ObjUtil.isNotEmpty(request.getScore())) {
            List<String> scores = StrUtil.splitTrim(request.getScore(), ",");
            crmComment.getParams().put("scores", scores);
            crmComment.setScore(null);
        }
        List<CrmComment> list = crmCommentService.selectCrmCommentList(crmComment);
        clearPage();
        return getDataTable(list);
    }

    /**
     * 导出评论列表
     */
    @Operation(summary = "导出评论列表")
    @PreAuthorize("@ss.hasPermi('system:comment:export')")
    @Log(title = "评论", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CrmCommentQueryRequest request) {
        CrmComment crmComment = BeanUtil.copyProperties(request, CrmComment.class);
        List<CrmComment> list = crmCommentService.selectCrmCommentList(crmComment);
        ExcelUtil<CrmComment> util = new ExcelUtil<CrmComment>(CrmComment.class);
        util.exportExcel(response, list, "评论数据");
    }

    /**
     * 获取评论详细信息
     */
    @Operation(summary = "获取评论详细信息")
    @PreAuthorize("@ss.hasPermi('system:comment:query')")
    @GetMapping(value = "/{commentId}")
    public AjaxResult getInfo(@PathVariable("commentId") Long commentId) {
        return success(crmCommentService.selectCrmCommentByCommentId(commentId));
    }

    /**
     * 新增评论
     */
    @Operation(summary = "新增评论")
    @PreAuthorize("@ss.hasPermi('system:comment:add')")
    @Log(title = "评论", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CrmComment crmComment) {
        return toAjax(crmCommentService.insertCrmComment(crmComment));
    }

    /**
     * 修改评论
     */
    @Operation(summary = "修改评论")
    @PreAuthorize("@ss.hasPermi('system:comment:edit')")
    @Log(title = "评论", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CrmComment crmComment) {
        return toAjax(crmCommentService.updateCrmComment(crmComment));
    }

    /**
     * 删除评论
     */
    @Operation(summary = "删除评论")
    @PreAuthorize("@ss.hasPermi('system:comment:remove')")
    @Log(title = "评论", businessType = BusinessType.DELETE)
    @DeleteMapping("/{commentIds}")
    public AjaxResult remove(@PathVariable Long[] commentIds) {
        return toAjax(crmCommentService.deleteCrmCommentByCommentIds(commentIds));
    }

    @Operation(summary = "同步评论")
    @PreAuthorize("@ss.hasPermi('system:comment:sync')")
    @Log(title = "评论", businessType = BusinessType.IMPORT)
    @PostMapping("/sync")
    public AjaxResult commentSync(@RequestHeader(name = "baidu-token", required = true) String token) {

        int pageNum = 1;
        String endTime = LocalDateTime.now().with(LocalTime.MAX).format(DateUtils.DFYMDHMSTZ);
        String startTime = LocalDateTime.now().with(LocalTime.MIN).format(DateUtils.DFYMDHMSTZ);
        clearPage();
        CrmComment comment = crmCommentService.getOne(Wrappers.<CrmComment>lambdaQuery().orderByDesc(CrmComment::getCreateTime).last("limit 1"));
        startTime = comment != null ? DateUtils.toLocalDateTime(comment.getCreateTime()).format(DateUtils.DFYMDHMSTZ) : startTime;
        do {
            String body = getCommentJson(pageNum, startTime, endTime,token);
            JSONObject result = JSON.parseObject(body);
            if (result.getIntValue("status") == 0) {
                BaiDuJianKangApi.PageResponse pageResponse = result.getObject("data", BaiDuJianKangApi.PageResponse.class);
                if (pageResponse.getTotal() > 0) {
                    ForkJoinPool forkJoinPool = new ForkJoinPool(20);
                    try{
                        forkJoinPool.submit(() -> {
                            pageResponse.getList().parallelStream().forEach(item -> {
                                CrmComment crmComment = JSON.parseObject(item, CrmComment.class);
                                JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(crmComment.getSkuInfo()));
                                Long skuId = jsonObject.getLong("skuId");
                                crmComment.setSkuInfo(jsonObject);
                                crmComment.setProductId(skuId);
                                if (!"该用户觉得商品很好，给出了5星好评".equals(crmComment.getContent())) {
                                    crmCommentService.saveOrUpdate(crmComment);
                                }
                            });
                        });
                        pageNum++;
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }finally {
                        forkJoinPool.shutdown();
                    }
                } else {
                    break;
                }
            }else {
                break;
            }
        } while (true);

        return success();
    }


    private String getCommentJson(Integer page, String startTime, String endTime, String token) {
        Map<String, String> map = Maps.newHashMap();
        map.put("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36");
        map.put("company-id", "1000002910");
        map.put("Cookie", ObjUtil.isNotEmpty(token) ? token : "BDUSS_BFESS=lSU2VzNVRKcUxlM0lTSTdHRGozU2tkcDVtSEtUWThhcmNVUHNjTEthWU53c2hvRUFBQUFBJCQAAAAAAAAAAAEAAADbWcw-eGlhb3poZW5nMDMyMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA01oWgNNaFoMz;");
        HttpResponse execute = null;
        BaiDuJianKangApi.DataRequest<BaiDuJianKangApi.CommentRequest> dataRequest = new BaiDuJianKangApi.DataRequest<>();
        BaiDuJianKangApi.CommentRequest commentRequest = new BaiDuJianKangApi.CommentRequest();
        commentRequest.setSellerId("1858059855061663744");
        commentRequest.setShopId("1858059855061663744");
        commentRequest.setSize(10000);
        commentRequest.setPage(page);
        commentRequest.setDefPraise(10);
        commentRequest.setStartTime(startTime);
        commentRequest.setEndTime(endTime);
        dataRequest.setData(commentRequest);
        try {
            execute = HttpUtil.createPost("https://jiankang.baidu.com/seller/comment/list")
                    .headerMap(map, true).setMethod(Method.POST)
                    .body(JSON.toJSONString(dataRequest))
                    .timeout(10000).execute();
            return execute.body();
        } finally {
            if (execute != null) {
                execute.close();
            }
        }
    }
}
